/*
 * Created by JFormDesigner on Sun Oct 23 19:33:06 CST 2022
 */

package cc.caiguang.png2ico;

import cc.caiguang.image4j.codec.ico.ICOEncoder;
import com.formdev.flatlaf.extras.FlatSVGUtils;
import net.miginfocom.swing.MigLayout;

import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author caiguang
 */
public class Win extends JFrame {
    ArrayList<JRadioButton> jRadioButtonList = new ArrayList();

    public void setImage(BufferedImage image) {
        this.image = image;
    }

    BufferedImage image = null;
    List<BufferedImage> bufferedImageList = null;

    public Win() {
        initComponents();

        jRadioButtonList.add(r256);
        jRadioButtonList.add(r64);
        jRadioButtonList.add(r48);
        jRadioButtonList.add(r40);
        jRadioButtonList.add(r32);
        jRadioButtonList.add(r24);
        jRadioButtonList.add(r20);
        jRadioButtonList.add(r16);

    }

    private void selectAll(ActionEvent e) {
        // TODO add your code here
        for (int i = 0; i < jRadioButtonList.size(); i++) {
            JRadioButton jr = jRadioButtonList.get(i);
            jr.setSelected(true);
        }
    }

    private void clear(ActionEvent e) {
        // TODO add your code here
        for (int i = 0; i < jRadioButtonList.size(); i++) {
            JRadioButton jr = jRadioButtonList.get(i);
            jr.setSelected(false);
        }
    }

    //平滑缩放BufferedImage图片
    public static BufferedImage scaleImage(BufferedImage sourceImg, int width, int height) {
        Image scaleInstance = sourceImg.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        bufferedImage.getGraphics().drawImage(scaleInstance, 0, 0, null);
        return bufferedImage;
    }

    private void exportIco(ActionEvent e) {
        // TODO add your code here
        bufferedImageList = new ArrayList<>();

        for (int i = 0; i < jRadioButtonList.size(); i++) {
            JRadioButton jRadioButton = jRadioButtonList.get(i);
            if (jRadioButton.isSelected()) {
                String text = jRadioButton.getText();
                int size = Integer.parseInt(text.split(" ")[0]);
//                System.out.println("你选择了 " + size + " x " + size);

//                bufferedImageList.add(ImageUtil.scaleImage(image, size, size));
                bufferedImageList.add(scaleImage(image, size, size));

            }
        }

        String uesrHome = System.getProperty("user.home");
        JFileChooser jFileChooser = new JFileChooser(uesrHome + "\\Pictures");
        jFileChooser.setMultiSelectionEnabled(false);
        jFileChooser.setDialogTitle("请选择要保存的位置");
        jFileChooser.addChoosableFileFilter(new FileNameExtensionFilter("图标ICO", "ico"));

        jFileChooser.showSaveDialog(this);
        File file = jFileChooser.getSelectedFile();

        if (file != null) {
            String fname = jFileChooser.getName(file);
            if (fname.indexOf(".ico") == -1) {
                file = new File(jFileChooser.getCurrentDirectory(), fname + ".ico");
            }

            File newFile = file;
            SwingUtilities.invokeLater(() -> {
                OutputStream outputStream = null;

                try {
                    int[] bpp = new int[bufferedImageList.size()];
                    boolean[] compress = new boolean[bufferedImageList.size()];
                    for (int i = 0; i < bufferedImageList.size(); i++) {
                        bpp[i] = 32;
                        compress[i] = true;
                    }
                    outputStream = new FileOutputStream(newFile);
                    ICOEncoder.write(bufferedImageList, bpp, compress, outputStream);
                    outputStream.close();

                } catch (IOException ex) {
                    if (outputStream != null) {
                        try {
                            outputStream.close();
                        } catch (IOException exc) {
                            throw new RuntimeException(exc);
                        }
                    }
                    throw new RuntimeException(ex);
                }
            });
        }


    }


    public JLabel getSrcLabel() {
        return srcLabel;
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
        srcLabel = new JLabel();
        rPanel = new JPanel();
        r16 = new JRadioButton();
        r20 = new JRadioButton();
        r24 = new JRadioButton();
        r32 = new JRadioButton();
        r40 = new JRadioButton();
        r48 = new JRadioButton();
        r64 = new JRadioButton();
        r256 = new JRadioButton();
        separator1 = new JSeparator();
        bPanel = new JPanel();
        selectAll = new JButton();
        clear = new JButton();
        exportIco = new JButton();

        //======== this ========
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setTitle("PNG转ICO - 作者主页：caiguang.cc");
        setResizable(false);
        setIconImages(FlatSVGUtils.createWindowIconImages(getClass().getResource("/logo.svg")));
        var contentPane = getContentPane();
        contentPane.setLayout(new MigLayout(
                "hidemode 3",
                // columns
                "[fill]" +
                        "[fill]" +
                        "[98,fill]" +
                        "[fill]",
                // rows
                "[]" +
                        "[]" +
                        "[]" +
                        "[]" +
                        "[]"));

        //---- srcLabel ----
        srcLabel.setText("请拖入一个正方形PNG图片");
        srcLabel.setPreferredSize(new Dimension(256, 256));
        srcLabel.setHorizontalAlignment(SwingConstants.CENTER);
        srcLabel.setHorizontalTextPosition(SwingConstants.CENTER);
        srcLabel.setBorder(new TitledBorder(new LineBorder(Color.gray, 1, true), "\u539f\u56fe"));
        srcLabel.setMaximumSize(new Dimension(256, 256));
        srcLabel.setMinimumSize(new Dimension(256, 256));
        contentPane.add(srcLabel, "cell 1 1 1 2");

        //======== rPanel ========
        {
            rPanel.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0, 0)), "\u9009\u62e9\u5c3a\u5bf8", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, Color.gray));
            rPanel.setLayout(new GridLayout(8, 0, 5, 5));

            //---- r16 ----
            r16.setText("16 x 16");
            rPanel.add(r16);

            //---- r20 ----
            r20.setText("20 x 20");
            rPanel.add(r20);

            //---- r24 ----
            r24.setText("24 x 24");
            rPanel.add(r24);

            //---- r32 ----
            r32.setText("32 x 32");
            rPanel.add(r32);

            //---- r40 ----
            r40.setText("40 x 40");
            rPanel.add(r40);

            //---- r48 ----
            r48.setText("48 x 48");
            rPanel.add(r48);

            //---- r64 ----
            r64.setText("64 x 64");
            rPanel.add(r64);

            //---- r256 ----
            r256.setText("256 x 256");
            rPanel.add(r256);
        }
        contentPane.add(rPanel, "");
        contentPane.add(separator1, "cell 1 3 2 1");

        //======== bPanel ========
        {
            bPanel.setLayout(new GridLayout(0, 3, 5, 5));

            //---- selectAll ----
            selectAll.setText("\u5168\u9009\u5c3a\u5bf8");
            selectAll.addActionListener(e -> selectAll(e));
            bPanel.add(selectAll);

            //---- clear ----
            clear.setText("\u6e05\u7a7a\u5c3a\u5bf8");
            clear.addActionListener(e -> clear(e));
            bPanel.add(clear);

            //---- exportIco ----
            exportIco.setText("\u5bfc\u51faICO");
            exportIco.addActionListener(e -> exportIco(e));
            bPanel.add(exportIco);
        }
        contentPane.add(bPanel, "cell 1 4 2 1");
        setSize(420, 365);
        setLocationRelativeTo(null);
        // JFormDesigner - End of component initialization  //GEN-END:initComponents
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
    private JLabel srcLabel;
    private JPanel rPanel;
    private JRadioButton r16;
    private JRadioButton r20;
    private JRadioButton r24;
    private JRadioButton r32;
    private JRadioButton r40;
    private JRadioButton r48;
    private JRadioButton r64;
    private JRadioButton r256;
    private JSeparator separator1;
    private JPanel bPanel;
    private JButton selectAll;
    private JButton clear;
    private JButton exportIco;
    // JFormDesigner - End of variables declaration  //GEN-END:variables
}
